package cn.jfstu.freenote.dao.base;


import cn.jfstu.freenote.entity.base.Pagination;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.mapping.ResultMapping;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.util.List;

/**
 * 自定义分页排序拦截器
 * @author 贾俊峰
 * @version 1.0
 * @date 2016/9/2 23:58
 */
@Intercepts({ @Signature(type = Executor.class,method = "query",args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class }) })
public class PageSortInterceptor extends PageHelper {
    
    private static final int MAPPED_STATEMENT_INDEX = 0;
    private static final int PARAMETER_INDEX        = 1;

    public Object intercept(Invocation invocation) throws Throwable {
        final Object[] queryArgs = invocation.getArgs();
        MappedStatement ms = (MappedStatement) queryArgs[MAPPED_STATEMENT_INDEX];
        Object parameter = queryArgs[PARAMETER_INDEX];
        if (!(parameter instanceof Pagination)) { return super.intercept(invocation); }
        Pagination domain = (Pagination) parameter;
        if (domain.getPaging()) {
            if (domain.getSortName () != null) {
                // 处理排序字段
                StringBuilder sortSql = new StringBuilder("");
                String dbField = null;
                // 查找数据库映射字段
                List<ResultMap> rm1 = ms.getResultMaps ();
                for ( ResultMap rm_1 : rm1 ) {
                    List<ResultMapping> rm2 = rm_1.getPropertyResultMappings ();
                    for ( ResultMapping rm_2 : rm2 ) {
                        if (rm_2.getProperty ().equals (domain.getSortName ())) {
                            dbField = rm_2.getColumn ();
                            break;
                        }
                    }
                }
                // 拼排序sql
                if (dbField != null) {
                    sortSql.append (dbField).append (" ").append (domain.getSortOrder () == null ? "ASC" : domain.getSortOrder ());
                }
                PageHelper.startPage(domain.getPageNum(), domain.getPageSize(), sortSql.toString());
                
            } else {
                PageHelper.startPage(domain.getPageNum(), domain.getPageSize());
            }
        }
        
        
        return super.intercept(invocation);
    }
    
}
